<?php

include_once("models/book.class.php");

class Model {
	public function __construct() {
		// khởi tạo dữ liệu sử dụng session
		if (!isset($_SESSION['datastore'])) {
			$_SESSION['datastore'] = array(
				'1'=>new Book("Jungle Book", "R. Kipling", "A classic book."),
				'2'=>new Book("Moonwalker", "J. Walker", ""),
				'4'=>new Book("PHP for Dummies", "Some Smart Guy", "")
			);
		}
	}

	public function getBookList() {
		return $_SESSION['datastore'];
	}

	public function getBook($key) {
		$allBooks = $this->getBookList();
		if (isset($allBooks[$key]))
			return $allBooks[$key];
		return NULL;
	}

	public function saveBook(&$bookstore) {
		$key = Request::getVar('bkey',null,'post');
		$title = Request::getVar('btitle','','post');
		$author = Request::getVar('bauthor','','post');
		$description = Request::getVar('bdescription','','post');
		
		if (!isset($key)) {
			echo 'Lỗi!';
		} else {
			if (!isset($bookstore[$key])) {
				// thêm mới book
			} else {
				// lưu book
				$bookstore[$key]->title = $title;
				$bookstore[$key]->author = $author;
				$bookstore[$key]->description = $description;
				echo "Đã lưu!";
			}
		}
	}

	public function deleteBook($key)
	{
		//xóa phần tử trong mảng theo key
		unset($_SESSION['datastore'][$key]);
	}

}


// class request

$GLOBALS['_REQUEST'] = array();

class Request {

	function getVar($name, $default = null, $hash = 'default') {
		// Ensure hash and type are uppercase
		$hash = strtoupper($hash);
		if ($hash === 'METHOD') {
			$hash = strtoupper($_SERVER['REQUEST_METHOD']);
		}
		// Get the input hash
		switch ($hash)
		{
			case 'GET':
				$input = &$_GET;
				break;
			case 'POST':
				$input = &$_POST;
				break;
			case 'FILES':
				$input = &$_FILES;
				break;
			case 'COOKIE':
				$input = &$_COOKIE;
				break;
			case 'ENV':
				$input = &$_ENV;
				break;
			case 'SERVER':
				$input = &$_SERVER;
				break;
			default:
				$input = &$_REQUEST;
				$hash = 'REQUEST';
				break;
		}		
		$var = (isset($input[$name]) && $input[$name] !== null) ? $input[$name] : $default;		
		return $var;
	}	
}